<?php

namespace App\Jobs\BlockPool;

use App\Models\Account;
use App\Models\Coin;
use App\Models\Leader;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LeaderJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    // 空间租赁订单 或 开始挖矿订单
    protected $order;


    public function __construct($order)
    {
        $this->order = $order;
    }

    public function handle()
    {
        try {
            logger('==推广奖励结算==');
            $this->leader();
        } catch (\Throwable $throwable) {
            Log::info($throwable);
        }
    }

    /**
     * 推荐奖励释放.
     */
    protected function leader()
    {

        logger('订单金额：' . $this->order->reward);
        $user = User::find($this->order->user_id);
        // 所有上级
        $parents = User::where('_lft', '<', $user->_lft)
            ->where('_rgt', '>', $user->_rgt)
            ->orderBy('id', 'desc')
            ->get();

        if ($parents->count()) {
            foreach ($parents as $k => $v) {
                $isLeader = Leader::where('user_id', $v->id)
                    ->where('order_id', $this->order->id)
                    ->first();
                if ($isLeader) {
                    continue;
                }

                $rate = 0;
                if ($k == 0) { // 直推
                    // 查询套餐类型
                    $rate = Setting::where('key', 'vip_1')->value('value');
                } elseif ($k == 1) {
                    $rate = Setting::where('key', 'vip_2')->value('value');
                }

                $leader_reward = bcmul($rate, $this->order->reward);

                

                logger("{$v->username}拿推荐奖励：{$leader_reward}");
                // 用户账户
                /** @var Account $account */
                $account = Account::firstOrCreate([
                    'user_id' => $v->id,
                    'coin_id' => 1,
                ])->refresh();


                // 领导奖明细
                $leader = new Leader();
                $leader->user_id = $v->id;
                $leader->child_user_id = $this->order->user_id;
                $leader->order_id = $this->order->id;
                $leader->total = $this->order->reward;
                $leader->rate = $rate;
                $leader->profit = $leader_reward;
                $leader->time = now();
                if ($leader->profit <= 0) {
                    continue;
                }



                DB::transaction(function () use ($leader, $account) {
                    $leader->save();

                    // 更新账户
                    /** @var Account $account */
                    $account = Account::lockForUpdate()->find($account->id);
                    $account->availableIncrement($leader->profit);
                    $account->type = '推荐奖励释放';
                    $account->action_id = $leader->id;
                    $account->save();
                });
            }
        }
    }
}
